import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:extended_image/extended_image.dart';
import 'package:image_editor/image_editor.dart';

import './custom_cupertino_scaffold.dart';
import './tap_opacity.dart';

class CropperImage extends StatefulWidget {
    String image;
    double ratio;
    CropperImage({Key? key,required this.image,this.ratio=1}) : super(key: key);

    @override
    _CropperImageState createState() => _CropperImageState();
}

class _CropperImageState extends State<CropperImage> {

    final GlobalKey<ExtendedImageEditorState> editorKey =GlobalKey<ExtendedImageEditorState>();
    bool _cropping=false;

    @override
    void initState() {
        super.initState();
    }

    confirm()async{
        if (_cropping) {
            return;
        }
        setState(() {
            _cropping=true;
        });
        Uint8List? fileData=await cropImageDataWithNativeLibrary(state: editorKey.currentState!);
        if(fileData!=null){
            final tempDir = await getTemporaryDirectory();
            final file = await new File('${tempDir.path}/${DateTime.now().millisecondsSinceEpoch}.png').create();
            file.writeAsBytesSync(fileData);
            Get.back(result:file);
        }
        setState(() {
            _cropping=false;
        });
    }

    Future<Uint8List?> cropImageDataWithNativeLibrary( {required ExtendedImageEditorState state}) async {
        print('native library start cropping');

        final Rect? cropRect = state.getCropRect();
        final EditActionDetails action = state.editAction!;

        final int rotateAngle = action.rotateAngle.toInt();
        final bool flipHorizontal = action.flipY;
        final bool flipVertical = action.flipX;
        final Uint8List img = state.rawImageData;

        final ImageEditorOption option = ImageEditorOption();

        if (action.needCrop) {
            option.addOption(ClipOption.fromRect(cropRect!));
        }

        if (action.needFlip) {
            option.addOption(
                FlipOption(horizontal: flipHorizontal, vertical: flipVertical));
        }

        if (action.hasRotateAngle) {
            option.addOption(RotateOption(rotateAngle));
        }

        final DateTime start = DateTime.now();
        final Uint8List? result = await ImageEditor.editImage(
            image: img,
            imageEditorOption: option,
        );

        print('${DateTime.now().difference(start)} ：total time');
        return result;
    }

    @override
    Widget build(BuildContext context) {
        return CustomCupertinoScaffold(
            titleText: "裁剪",
            navBackgroundColor:Colors.black,
            backgroundColor: Colors.black,
            trailing:TapOpacity(
                child: _cropping?SizedBox(
                    height: 15.w,
                    width: 15.w,
                    child: CircularProgressIndicator(valueColor:new AlwaysStoppedAnimation(Colors.white),strokeWidth: 2.w),
                ):Text("完成",style: TextStyle(fontSize: 15.sp,color:Colors.white)),
                onTap: (){
                    confirm();
                },
            ),
            body:Center(
                child:ExtendedImage(
                    image: renderImage(),
                    fit: BoxFit.contain,
                    mode: ExtendedImageMode.editor,
                    extendedImageEditorKey: editorKey,
                    initEditorConfigHandler: (state) {
                        return EditorConfig(
                            maxScale: 8.0,
                            cropRectPadding: EdgeInsets.all(20.0),
                            hitTestSize: 20.0,
                            cropAspectRatio: widget.ratio,
                            editorMaskColorHandler:(context, pointerDown) {
                                return Colors.black.withOpacity(pointerDown ? 0.2 : 0.3);
                            },
                        );
                    },
                )
            )
        );
    }

    ImageProvider<Object> renderImage(){
        if(widget.image.contains('http')){
            return ExtendedNetworkImageProvider(widget.image,cacheRawData:true);
        }else{
            return ExtendedFileImageProvider(File(widget.image),cacheRawData:true);
        }
    }
}
